package lcr;

public class Test0192 {
}

class Solution192_1 {
    public int myAtoi(String str) {
        int length = str.length();
        char[] chars = str.toCharArray();
        int ans = 0;
        int i = 0;

        while (i < length&&chars[i]==' '){
            i++;
        }
        if (i>=length){
            return 0;
        }

        int limit= Integer.MAX_VALUE;
        int flag = 1;
        if (chars[i]=='-'||chars[i]=='+'){
            if (chars[i]=='-') {
                flag = -1;
                limit = Integer.MIN_VALUE;
            }

            i++;
        }

        while (i<length&&chars[i]>='0'&&chars[i]<='9'){
            int now = (chars[i]-'0')*flag;
            if (flag<0) {
                if ((limit-now)/10>ans){
                    return limit;
                }else {
                    ans = ans*10+now;
                }
            }else {
                if ((limit-now)/10<ans){
                    return limit;
                }else {
                    ans = ans*10+now;
                }
            }

            i++;
        }

        return ans;
    }
}
